package com.huluobo.a2206douyindemo.videos;

import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2206douyindemo.R;
import com.huluobo.a2206douyindemo.adapter.CommentAdapter;
import com.huluobo.a2206douyindemo.adapter.MultiVideoAdapter;
import com.huluobo.a2206douyindemo.databinding.FragmentVideosBinding;
import com.huluobo.a2206douyindemo.live.LiveActivity;
import com.huluobo.a2206douyindemo.login.LoginActivity;
import com.huluobo.base.bean.CommentBeanResult;
import com.huluobo.base.bean.VideoBeanResult;
import com.huluobo.base.db.AppDBUtils;
import com.huluobo.base.mvvm.BaseMVVMFragment;
import com.huluobo.base.net.Const;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.List;

public class VideosFragment extends BaseMVVMFragment<FragmentVideosBinding, VideoViewModel> {
    //视频的适配器
    private MultiVideoAdapter videoAdapter;
    //视频的数据源
//    private List<VideoBeanResult.VideoBean> videoBeanList = new ArrayList<>();
    private CommentAdapter commentAdapter;
    private List<CommentBeanResult.CommentBean> commentBeanList = new ArrayList<>();

    //当前播放的是哪个item的下标
    private int currentPosition = 0;
    private StandardGSYVideoPlayer player;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_videos;
    }

    @Override
    protected void initData() {
        viewModel.getVideoList(2, 10);

        viewModel.getVideoListSuccess.observe(this, videoBeanResult -> {
            if (videoBeanResult.getCode() == 200) {
                videoAdapter.getData().clear();
                videoAdapter.getData().addAll(videoBeanResult.getData());
                videoAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(videoBeanResult.getMessage());
            }
        });

        viewModel.getVideoListFailed.observe(this, s -> {
            Log.i("TagA", "获取视频列表失败:" + s);
        });

        viewModel.likeVideoSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                //从数据源中修改为已点赞
                videoAdapter.getData().get(currentPosition).setDianzan(1);
                videoAdapter.notifyDataSetChanged();
            }
        });

        viewModel.likeVideoFailed.observe(this, s -> {
            Log.i("TagA", "点赞失败:" + s);
        });

        viewModel.noLikeVideoSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                //从数据源中修改为已点赞
                videoAdapter.getData().get(currentPosition).setDianzan(0);
                videoAdapter.notifyDataSetChanged();
            }
        });

        viewModel.noLikeVideoFailed.observe(this, s -> {
            Log.i("TagA", "取消点赞失败:" + s);
        });

        viewModel.followAuthSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setGuanzhu(1);
                videoAdapter.notifyDataSetChanged();
            }
        });

        viewModel.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        viewModel.getCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                commentBeanList.clear();
                commentBeanList.addAll(commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        viewModel.getCommentFailed.observe(this, s -> {
            Log.i("TagA", "获取评论列表失败::" + s);
        });

        viewModel.sendCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                //在评论的第0位添加最新的数据
                commentAdapter.getData().addAll(0, commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();

                //发送成功,清空输入框
                EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_videos_comment_et);
                assert editText != null;
                editText.setText("");
            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        viewModel.sendCommentFailed.observe(this, s -> {
            Log.i("TagA", "发送评论失败::" + s);
        });
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        binding.videoRv.setLayoutManager(layoutManager);
        videoAdapter = new MultiVideoAdapter();
        binding.videoRv.setAdapter(videoAdapter);

        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(binding.videoRv);

        binding.videoRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                //当rv滑动时,获取当前展示的item的下标
                currentPosition = layoutManager.findFirstVisibleItemPosition();
                player = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_videos_gsyPlayer);
                if (player != null) {
                    //如果播放器不为空,自动播放
//                    player.startPlayLogic();
                }
            }
        });

        //添加item的点击事件id
        videoAdapter.addChildClickViewIds(R.id.item_videos_like_iv, R.id.item_videos_add_iv,
                R.id.item_videos_comment_iv, R.id.item_videos_close_iv, R.id.item_videos_comment_send_iv,
                R.id.item_videos_share_iv, R.id.item_videos_collect_iv, R.id.item_videos_live_cl,
                R.id.item_videos_full_cl);

        //设置item的点击事件
        videoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            //只要点击了item中的任何view都拿到对应的videoBean
            VideoBeanResult.VideoBean videoBean = (VideoBeanResult.VideoBean) adapter.getData().get(position);
            String token = SPUtils.getInstance().getString(Const.PARAM_TOKEN);
            if (token.isEmpty()) {
                //没登录过
                Intent intent = new Intent(requireContext(), LoginActivity.class);
                startActivity(intent);
                return;
            }
            switch (view.getId()) {
                case R.id.item_videos_like_iv:
                    likeVideo(videoBean);
                    break;
                case R.id.item_videos_add_iv:
                    followAuth(videoBean);
                    break;
                case R.id.item_videos_comment_iv:
                    openComment(videoBean);
                    break;
                case R.id.item_videos_close_iv:
                    closeComment();
                    break;
                case R.id.item_videos_comment_send_iv:
                    sendComment(videoBean);
                    break;
                case R.id.item_videos_share_iv:
                    shareVideo(videoBean);
                    break;
                case R.id.item_videos_collect_iv:
                    AppDBUtils.getInstance().getVideoDao().insertVideoInfo(videoBean);
                    break;
                case R.id.item_videos_full_cl:
                    fullScreenPlayer(videoBean);
                    break;
                case R.id.item_videos_live_cl:
                    toLive(videoBean);
                    break;
            }
        });
    }

    //跳转直播间
    private void toLive(VideoBeanResult.VideoBean videoBean) {
        Intent intent = new Intent(requireContext(), LiveActivity.class);
        intent.putExtra("videoBean", videoBean);
        startActivity(intent);
    }

    //设置全屏播放
    private void fullScreenPlayer(VideoBeanResult.VideoBean videoBean) {
        if (player != null) {
            player.setRotateViewAuto(true);//设置自动翻转屏幕
            player.startWindowFullscreen(requireContext(), false, false);//设置全屏,是否显示动作条,是否显示状态栏
            player.startPlayLogic();
        }
    }

    //分享
    private void shareVideo(VideoBeanResult.VideoBean videoBean) {
        //缩略图
        UMImage umImage = new UMImage(requireContext(), videoBean.getVideomainimg());
        umImage.compressStyle = UMImage.CompressStyle.SCALE;//压缩图片大小

        UMWeb web = new UMWeb(videoBean.getVideopath());//分享的视频地址
        web.setThumb(umImage);//缩略图
        web.setTitle(videoBean.getAuthname());//设置分享标题
        web.setDescription(videoBean.getCaption());//设置分享描述

        new ShareAction(requireActivity())
                .withMedia(web)//填入分享内容
                .open();
    }

    //发评论
    private void sendComment(VideoBeanResult.VideoBean videoBean) {
        //获取输入框
        EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et);
        assert editText != null;
        String msgString = editText.getText().toString();
        if (!TextUtils.isEmpty(msgString)) {
            viewModel.sendComment(videoBean.getId(), msgString);
        } else {
            ToastUtils.showLong("评论内容不能为空");
        }
    }

    private void closeComment() {
        //获取评论布局
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll);
        assert commentLayout != null;
        commentLayout.setVisibility(View.VISIBLE);
        //加载动画
        Animation animationOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out);
        animationOut.setDuration(500);
        commentLayout.startAnimation(animationOut);
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                commentLayout.setVisibility(View.GONE);
                //恢复RecyclerView的拦截事件
                binding.videoRv.setIntercept(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void openComment(VideoBeanResult.VideoBean videoBean) {
        //展示评论布局的同时,拦截RecyclerView的事件
        binding.videoRv.setIntercept(false);
        //获取评论布局
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll);
        assert commentLayout != null;
        commentLayout.setVisibility(View.VISIBLE);
        //加载动画
        Animation animationIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in);
        animationIn.setDuration(500);
        commentLayout.startAnimation(animationIn);

        //初始化评论布局
        RecyclerView commentRv = (RecyclerView) videoAdapter.getViewByPosition(currentPosition,
                R.id.item_videos_comment_rv);
        assert commentRv != null;
        commentRv.setLayoutManager(new LinearLayoutManager(requireContext()));
        commentAdapter = new CommentAdapter(commentBeanList);
        commentRv.setAdapter(commentAdapter);

        animationIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                viewModel.getComments(videoBean.getId());
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    //关注
    private void followAuth(VideoBeanResult.VideoBean videoBean) {
        viewModel.followAuth(videoBean.getAuthname());
    }

    //点赞和取消点赞
    private void likeVideo(VideoBeanResult.VideoBean videoBean) {
        if (videoBean.getDianzan() == 0) {
            //未点赞,需要调用点赞方法
            viewModel.likeVideo(videoBean.getId());
        } else {
            //已点赞,需要调用取消点赞方法
            viewModel.noLikeVideo(videoBean.getId());
        }
    }

    @Override
    protected Class<VideoViewModel> getViewModel() {
        return VideoViewModel.class;
    }
}